package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.shop.domain.MetaverseShop;
import com.ruoyi.shop.service.IMetaverseShopService;
import com.ruoyi.shopManager.domain.MetaverseShopManager;
import com.ruoyi.shopManager.service.IMetaverseShopManagerService;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.gameRecord.domain.MetaverseGameRecord;
import com.ruoyi.gameRecord.service.IMetaverseGameRecordService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import springfox.documentation.spring.web.json.Json;

/**
 * 创建房间Controller
 *
 * @author ruoyi
 * @date 2023-10-18
 */
@RestController
@RequestMapping("/metaverse-gameRecord/gameRecord")
public class MetaverseGameRecordController extends BaseController
{
    @Autowired
    private IMetaverseGameRecordService metaverseGameRecordService;
    @Autowired
    private IMetaverseShopManagerService shopManagerService;
    @Resource
    private MongoTemplate mongoTemplate;
    @Autowired
    private IMetaverseShopService shopService;

    /**
     * 查询创建房间列表
     */
    @PreAuthorize("@ss.hasPermi('metaverse-gameRecord:gameRecord:list')")
    @GetMapping("/list")
    public TableDataInfo list(MetaverseGameRecord metaverseGameRecord)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (user.getDeptId()==202){
            Long shopManagerId = user.getHostId();
            if (shopManagerId != null){
                List<MetaverseShopManager> shopManagerList = shopManagerService.selectMetaverseShopManagerListAOP(shopManagerId);
                if (!shopManagerList.isEmpty()){
                    for (MetaverseShopManager shopManager : shopManagerList){
                        if (shopManagerId == shopManager.getShopManagerId()){
                            startPage();
                            List<MetaverseGameRecord> list = metaverseGameRecordService.selectMetaverseGameRecordListAop(shopManager.getShopId());
                            return getDataTable(list);
                        }
                    }
                }else {
                    return null;
                }
            }
        }else if (user.getDeptId() == 101){
            Long groupId = user.getHostId();
            List<MetaverseShop> shopList = shopService.selectMetaverseShopListAop(groupId);
            if (!shopList.isEmpty()){
                List<Long> id = new ArrayList<>();
                for (MetaverseShop shop : shopList){
                    if (shop.getGroupId() == groupId){
                        long shopId = shop.getShopId();
                        id.add(shopId);
                    }
                }
                startPage();
                List<MetaverseGameRecord> list = metaverseGameRecordService.selectMetaverseGameRecordListAbc(id);
                return getDataTable(list);
            }else {
                return null;
            }
        }
        startPage();
        List<MetaverseGameRecord> list = metaverseGameRecordService.selectMetaverseGameRecordList(metaverseGameRecord);
        return getDataTable(list);
    }

    /**
     * 导出创建房间列表
     */
    @PreAuthorize("@ss.hasPermi('metaverse-gameRecord:gameRecord:export')")
    @Log(title = "创建房间", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MetaverseGameRecord metaverseGameRecord)
    {
        List<MetaverseGameRecord> list = metaverseGameRecordService.selectMetaverseGameRecordList(metaverseGameRecord);
        ExcelUtil<MetaverseGameRecord> util = new ExcelUtil<MetaverseGameRecord>(MetaverseGameRecord.class);
        util.exportExcel(response, list, "创建房间数据");
    }

    /**
     * 获取创建房间详细信息
     */
    @PreAuthorize("@ss.hasPermi('metaverse-gameRecord:gameRecord:query')")
    @GetMapping(value = "/{gameNum}")
    public AjaxResult getInfo(@PathVariable("gameNum") Long gameNum) throws JsonProcessingException {
        MetaverseGameRecord gameRecord = metaverseGameRecordService.selectMetaverseGameRecordByGameNum(gameNum);
        System.out.println("状态：" + gameRecord.getStatus());
        if (gameRecord != null){
            if (gameRecord.getGameId()==1){
                Query query = Query.query(Criteria.where("gameNum").is(gameNum));
                List<MetaverseGameRecord> sorts = mongoTemplate.find(query,MetaverseGameRecord.class,"money_counting_game_sort");
                sorts.forEach(System.out::println);
                System.out.println("size is " + sorts.size());
                if (!sorts.isEmpty()) {
                    MetaverseGameRecord sortedGameRecord = sorts.get(0); // 取第一个排序记录
                    ObjectMapper objectMapper = new ObjectMapper();
                    if (sortedGameRecord.getSort().size() > 0) {
                        JsonNode firstPlaceJson = objectMapper.readTree(sortedGameRecord.getSort().get(0));
                        String nickNameOne = firstPlaceJson.get("nickName").asText();
                        gameRecord.setNickNameOne(nickNameOne);
                    }
                    if (sortedGameRecord.getSort().size() > 1) {
                        JsonNode secondPlaceJson = objectMapper.readTree(sortedGameRecord.getSort().get(1));
                        String nickNameTwo = secondPlaceJson.get("nickName").asText();
                        gameRecord.setNickNameTwo(nickNameTwo);
                    }
                    if (sortedGameRecord.getSort().size() > 2) {
                        JsonNode thirdPlaceJson = objectMapper.readTree(sortedGameRecord.getSort().get(2));
                        String nickNameThree = thirdPlaceJson.get("nickName").asText();
                        gameRecord.setNickNameThree(nickNameThree);
                    }
                }
            }else if (gameRecord.getGameId() == 2){
                Query query = Query.query(Criteria.where("gameNum").is(gameNum));
                List<MetaverseGameRecord> sorts = mongoTemplate.find(query,MetaverseGameRecord.class,"roll_the_dice_sort");
                sorts.forEach(System.out::println);
                System.out.println("size is " + sorts.size());
                if (!sorts.isEmpty()) {
                    MetaverseGameRecord sortedGameRecord = sorts.get(0); // 取第一个排序记录
                    ObjectMapper objectMapper = new ObjectMapper();
                    if (sortedGameRecord.getSort().size() > 0) {
                        JsonNode firstPlaceJson = objectMapper.readTree(sortedGameRecord.getSort().get(0));
                        String nickNameOne = firstPlaceJson.get("nickName").asText();
                        gameRecord.setNickNameOne(nickNameOne);
                    }
                    if (sortedGameRecord.getSort().size() > 1) {
                        JsonNode secondPlaceJson = objectMapper.readTree(sortedGameRecord.getSort().get(1));
                        String nickNameTwo = secondPlaceJson.get("nickName").asText();
                        gameRecord.setNickNameTwo(nickNameTwo);
                    }
                    if (sortedGameRecord.getSort().size() > 2) {
                        JsonNode thirdPlaceJson = objectMapper.readTree(sortedGameRecord.getSort().get(2));
                        String nickNameThree = thirdPlaceJson.get("nickName").asText();
                        gameRecord.setNickNameThree(nickNameThree);
                    }
                }
            } else if (gameRecord.getGameId() == 3) {
                Query query = Query.query(Criteria.where("gameNum").is(gameNum));
                MetaverseGameRecord sorts = mongoTemplate.findOne(query,MetaverseGameRecord.class,"wine_king_record");
                if (sorts!=null){
                    if (!sorts.getWinPlayer().equals("")&&sorts.getWinPlayer()!=null) {
                        ObjectMapper objectMapper = new ObjectMapper();
                        JsonNode firstPlaceJson = objectMapper.readTree(sorts.getWinPlayer());
                        String nickNameOne = firstPlaceJson.get("nickName").asText();
                        gameRecord.setNickNameOne(nickNameOne);
                    }else{
                        return success(gameRecord);
                    }
                } else if (sorts == null){
                    return success(gameRecord);
                }
            }else if (gameRecord.getGameId() == 4) {
                Query query = Query.query(Criteria.where("gameNum").is(gameNum));
                List<MetaverseGameRecord> sorts = mongoTemplate.find(query,MetaverseGameRecord.class,"size_game_sort");
                if (!sorts.isEmpty()){
                    List<String> nickNameOne = new ArrayList<>();
                    for (MetaverseGameRecord record : sorts){
                       if (record.getWinPlayer()!=null){
                           ObjectMapper objectMapper = new ObjectMapper();
                           JsonNode firstPlaceJson = objectMapper.readTree(record.getWinPlayer());
                           String nickName = firstPlaceJson.get("nickName").asText();
                           nickNameOne.add(nickName);
                       }
                    }
                    gameRecord.setNickNameS(nickNameOne);
                }

            }
        }
        return success(gameRecord);
    }

    /**
     * 新增创建房间
     */
    @PreAuthorize("@ss.hasPermi('metaverse-gameRecord:gameRecord:add')")
    @Log(title = "创建房间", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MetaverseGameRecord metaverseGameRecord)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (!user.isAdmin()){
            metaverseGameRecord.setShopManagerId(user.getHostId());
            MetaverseShopManager shopManager = shopManagerService.selectMetaverseShopManagerByShopManagerId(metaverseGameRecord.getShopManagerId());
            metaverseGameRecord.setShopId(shopManager.getShopId());
        }
        metaverseGameRecord.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        int num = metaverseGameRecordService.insertMetaverseGameRecord(metaverseGameRecord);
        String url = " http://192.168.1.29:8083/screen/game/createGameNumber";
        MetaverseGameRecord record = new MetaverseGameRecord(metaverseGameRecord.getGameNum(),
                metaverseGameRecord.getGameId(),
                metaverseGameRecord.getGameStartTime(),
                metaverseGameRecord.getGameDuration(),
                metaverseGameRecord.getGameTitle(),
                metaverseGameRecord.getShopManagerId(),
                metaverseGameRecord.getShopId(),
                metaverseGameRecord.getPrizeOne(),
                metaverseGameRecord.getPrizeTwo(),
                metaverseGameRecord.getPrizeThree(),
                metaverseGameRecord.getStatus(),
                metaverseGameRecord.getPlayerCountMin(),
                metaverseGameRecord.getPlayerCountTotal(),
                metaverseGameRecord.getCost(),
                metaverseGameRecord.getGameCount(),
                metaverseGameRecord.getNickNameOne(),
                metaverseGameRecord.getNickNameTwo(),
                metaverseGameRecord.getNickNameThree());

        String result2 = HttpRequest.post(url)
            .form(JSONUtil.parseObj(record))//表单内容
            .timeout(20000)//超时，毫秒
            .execute().body();
        return toAjax(num);
    }

    /**
     * 修改创建房间
     */
    @PreAuthorize("@ss.hasPermi('metaverse-gameRecord:gameRecord:edit')")
    @Log(title = "创建房间", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MetaverseGameRecord metaverseGameRecord)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        metaverseGameRecord.setUpdateBy(user.getUserName());
        return toAjax(metaverseGameRecordService.updateMetaverseGameRecord(metaverseGameRecord));
    }


    /**
     * 删除创建房间
     *
    /**
     *
     * 修改游戏状态
     * @param gameNum
     * @return
     */
    @PreAuthorize("@ss.hasPermi('metaverse-gameRecord:gameRecord:edit')")
    @Log(title = "创建房间", businessType = BusinessType.UPDATE)
    @GetMapping("/update/{gameNum}")
    public AjaxResult updateStatus(@PathVariable("gameNum") Long gameNum ){
        int num = metaverseGameRecordService.updateStatus(gameNum);
        if (num>0){
            SysUser user = SecurityUtils.getLoginUser().getUser();
            MetaverseGameRecord gameRecord = metaverseGameRecordService.selectMetaverseGameRecordByGameNum(gameNum);
            gameRecord.setUpdateBy(user.getUserName());
        }

        String url = " http://192.168.1.29:8088/socket/game/startGame?id=" + gameNum;

        String result2 = HttpRequest.get(url)
            .form(JSONUtil.parseObj(gameNum))//表单内容
            .timeout(20000)//超时，毫秒
            .execute().body();
            return toAjax(num);
        }
    }
